﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;

namespace RazorTemplateEngine
{
    public class TemplatePathResolver
    {
        private string _additionalsearchPath;

        public TemplatePathResolver(string additionalSearchPath)
        {
            _additionalsearchPath = additionalSearchPath;
        }


        public bool FileExist(string path)
        {
            if (string.IsNullOrEmpty(path)) throw new ArgumentNullException("path");
            return System.IO.File.Exists(path) || System.IO.File.Exists(Path.Combine(_additionalsearchPath, path));
        }

        public TemplateFile ReadTemplate(string path)
        {
            if(string.IsNullOrEmpty(path)) throw new ArgumentNullException("path");
            
            FileStream fs;
            FileInfo fileInfo;
            string AbsolutlyPath = GetFileAbsolutlyPath(path);
            if (string.IsNullOrEmpty(AbsolutlyPath)) return null;
            fs = new FileStream(AbsolutlyPath, FileMode.Open);
            fileInfo = new FileInfo(AbsolutlyPath);
            string returnTemplate = string.Empty;
            StreamReader sr = null;
            try{
                sr = new StreamReader(fs,Encoding.Default,true);
                returnTemplate = sr.ReadToEnd();
            }
            catch(Exception ex)
            {
                throw ex;
            }
            finally
            {
                if(sr != null) sr.Close();
                if(fs !=  null) fs.Close();
            }
            return new TemplateFile {
                FileItself = fileInfo,
                FileContent = returnTemplate
            };
        }

        public FileInfo GetFileInfo(string path)
        {
            if (string.IsNullOrEmpty(path)) throw new ArgumentNullException("path");
            string AbsolutlyPath = GetFileAbsolutlyPath(path);
            if (string.IsNullOrEmpty(AbsolutlyPath)) return null;
            return new FileInfo(AbsolutlyPath);
        }

        private string GetFileAbsolutlyPath(string path)
        {
            if (string.IsNullOrEmpty(path)) throw new ArgumentNullException("path");
            if (System.IO.File.Exists(path))
            {
                return path;
            }
            else if (System.IO.File.Exists(Path.Combine(_additionalsearchPath, path)))
            {
                return Path.Combine(_additionalsearchPath, path);
            }
            else
                return null;
 
        }
    }
}
